<?php

class CmsController extends BaseClass
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $title;	//Page Title
	public $layout = 'main';
	
	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			//'postOnly + delete', // we only allow deletion via POST request
		);
	}
	
	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions' => array('index', 'view', 'delete', 'process', 'admin', 'update', 'removeImage'),
				'users' => $this->getAdmins(),
			),
			array('deny', // deny other user to perform actions
					'actions' => array('index', 'view', 'delete', 'process', 'admin', 'update', 'removeImage'),
					'users' => array('*'),
			),
		);
	}
	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$model=new Cms();
		$this->title = Yii::app()->name."-CMS";
		$model->unsetAttributes();
		
		if(isset($_GET['Cms']))
			$model->attributes = $_GET['Cms'];

		//$this->pr($_GET);
		 
		$this->render('index',array(
			'model'=>$model,
		));
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->title = Yii::app()->name."-view Page";
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionAdd()
	{
		$model = new Cms;
		$this->title = Yii::app()->name."-Add Page";
		if(isset($_POST['Cms'])){
			
			$model->attributes = $_POST['Cms'];
			$model->created = date('Y-m-d H:i:s');
			$model->content = $_POST['Cms']['content'];
			
			if($model->validate()){
				if($model->save(false)){
					
					if ( isset($_FILES['Cms']['name']['image']) && !empty($_FILES['Cms']['name']['image']) ){
						$newName = $this->generateNewNameOfImage($_FILES['Cms']['name']['image']);
						move_uploaded_file($_FILES['Cms']['tmp_name']['image'], './images/'.$newName);
						@chmod('./images/', 0777);
							
						if( isset($model->image) && !empty($model->image) ){
							if (file_exists('./images/'.$model->image)){
								unlink('./images/'.$model->image);
							}
						}
					
						$model->image = $newName;
						$model->update();
					}
					
					Yii::app()->user->setFlash('success', 'Page successfully created');
					$this->redirect(Yii::app()->getBaseUrl().'/admin/cms');
				} 
			}
		}
		$bgColor = '';
		$this->render('create',array(
			'model'=>$model,
			'bgColor'=> $bgColor
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate() {
		$this->title = Yii::app()->name." - Update Page";
		if( isset($_REQUEST['id']) && !empty($_REQUEST['id']) ){
			
			$model=$this->loadModel($_REQUEST['id']);
			$bgColor = '';
			if ( empty($model->bg_color) ){
				$isMenuItem = Menuitems::model()->findByAttributes(array('page_id'=>$model->id));
				
				if ( isset($isMenuItem) && !empty($isMenuItem) ){
					$parentId = Menuitems::model()->findByPk($isMenuItem->id)->parent;
					$pageId = Menuitems::model()->findByPk($parentId);
				
					if( isset($pageId) && !empty($pageId)){
						$bgColor = Cms::model()->findByPk($pageId->page_id)->bg_color;
					}
				}
			} else {
				$bgColor = $model->bg_color;
			}
			
			
			if(isset($_POST['Cms'])){
				$model->attributes = $_POST['Cms'];
				$model->content = $_POST['Cms']['content'];
				$model->modified = date('Y-m-d H:i:s');
				
				if($model->validate()){
					
					if($model->save(false)){
						
						if ( isset($_FILES['Cms']['name']['image']) && !empty($_FILES['Cms']['name']['image']) ){
							$newName = $this->generateNewNameOfImage($_FILES['Cms']['name']['image']);
							move_uploaded_file($_FILES['Cms']['tmp_name']['image'], './images/'.$newName);
							@chmod('./images/', 0777);
							
							if( isset($model->image) && !empty($model->image) ){
								if (file_exists('./images/'.$model->image)){
									@unlink('./images/'.$model->image);
								}
							}
								
							$model->image = $newName;
							$model->update();
						}
						
						Yii::app()->user->setFlash('success', 'Page successfully Updated');
						$this->redirect(Yii::app()->getBaseUrl().'/admin/cms');
					} 
				 } 
			}

			$this->render('update',array(
				'model'=>$model,
				'bgColor' => $bgColor
			));
		}
	}
	
	public function actionRemoveImage(){
		
		if ( isset($_REQUEST['image']) && !empty($_REQUEST['image']) ){
			
			$model = Cms::model()->findByPk($_REQUEST['id']);
			
			if ($model){
				if (@unlink('./images/'.$model->image)){
					$model->image = '';
					$model->update();
					echo 'success';
				} else{
					echo 'error';
				}
			}
			exit();
		}
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Cms('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Cms']))
			$model->attributes=$_GET['Cms'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}
	public function actionProcess(){
		$model = new Cms();
		if($_POST['pageAction'] == 'delete')
		{
			$criteria = new CDbCriteria;
			$criteria->addInCondition('id',$_POST['contact']);
			
			if(Cms::model()->deleteAll($criteria)) {
				Yii::app()->user->setFlash('success','Record (s) Successfully Deleted');
				$this->redirect(Yii::app()->getBaseUrl().'/admin/cms');
			}
			else {
				Yii::app()->user->setFlash('error','Record (s) not Deleted');
				$this->redirect(Yii::app()->getBaseUrl().'/admin/cms');
			}
		}
	}
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Cms the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Cms::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param Cms $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='cms-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
